#ifndef _TCPCONDUIT_H_
#define _TCPCONDUIT_H_

#include "Network.h"

struct evbuffer;
struct bufferevent;

namespace Network
{
	class TcpSlaveServer;
	class TcpConduit
	{
		friend class TcpSlaveServer;
	public:
		TcpConduit(int, TcpSlaveServer *, int);
		virtual ~TcpConduit();
		virtual void send(const void *, int);
		void getAddr(struct sockaddr_in *);
		void closeConn();
		void forceClose();
		inline int fd() {return _socket;}
		void pendClose();
		inline int id() {return _uid;}

		virtual bool active() { return true; }

	protected:
		/* len - input the length of buffer, output the length of packet that parsed out
		   return: packet command */
		virtual UInt16 parsePacket(struct evbuffer * buf, int &off, int &len) { return 0; }

		/* cmd - packet command
		   len - length of buffer
		   buf - buffer without header */
		virtual void onRecv(UInt16 cmd, int len, void * buf) {}
		virtual void onConnected() {}
		virtual void onDisconnected() {}

	private:
		static void _readcb( struct bufferevent *, void * arg );
		static void _writecb( struct bufferevent *, void * arg );
		static void _eventcb( struct bufferevent *, short wht, void * arg );

		void on_read();
		void on_write();
		void on_event(short);

	protected:
		int _socket;
		TcpSlaveServer * _host;
		struct bufferevent * _bev;
		bool _pendclose;

		int _uid;
	};
}

#endif // _TCPCONDUIT_H_
